/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import utility.ConnectDB;
import model.KhachHang;

/**
 *
 * @author Dom
 */
public class KhachHangController {
    public  static void ShowTable(JTable parent) throws SQLException
    {
        String sql = "SELECT * FROM KhachHang";
        ResultSet bang = ConnectDB.getResultSet(sql);
        
        ResultSetMetaData rsmd = bang.getMetaData();
        
        int column = rsmd.getColumnCount(); //Số cột
        
        DefaultTableModel model = new DefaultTableModel();  //Model đệm trước khi đẩy vào JTable
        
        //Lấy tiêu đề các cột và gán vào model
        String cname[] = new String[column];
        for (int i=0;i<column;i++)
            cname[i]=rsmd.getColumnName(i+1);
        model.setColumnIdentifiers(cname);
        
        
        //Lấy dữ liệu
        while (bang.next())
        {
            String record[] = new String[column];
            for (int i = 0; i<column;i++)
                record[i]=bang.getString(i+1);
            
            model.addRow(record);
            
        }
        //Đẩy model lên JTable
        parent.setModel(model);
    }
    
    public static void Them(KhachHang kh)
    {
         String sql = "INSERT INTO KHACHHANG(HoTen, DiaChi, GioiTinh, CMND, SDT) VALUES (";
            sql = sql + "'" + kh.getHoTen() + "'";
            sql = sql + ",'" + kh.getDiachi() + "'";
            sql = sql + ",'" + kh.getGioiTinh() + "'";
            sql = sql + ",'" + kh.getCMND() + "'";
            sql = sql + ",'" + kh.getDienThoai() + "'";
            sql += ")";
            
            ConnectDB.getResultSet(sql);
            //System.out.println(sql);
    }
    
    public static void Delete(int MaKH)
    {
        String sql = "DELETE FROM KHACHHANG WHERE MaKH =" + MaKH;
        ConnectDB.getResultSet(sql);
    }
    
    public static void Update(KhachHang kh)
    {
          String sql = "UPDATE KHACHHANG SET HoTen = ";
            sql = sql + "'" + kh.getHoTen() + "'";
            sql = sql + ",DiaChi = ";
            sql = sql + "'" + kh.getDiachi() + "'";
            sql = sql + ",CMND = ";
            sql = sql + "'" + kh.getCMND() + "'";
            sql = sql + ",SDT = ";
            sql = sql + "'" + kh.getDienThoai() + "'";
            sql = sql + ",GioiTinh =";
            sql = sql + "'" + kh.getGioiTinh() + "'";
            sql += "WHERE MaKH=";
            sql += kh.getMaKH();
            
            ConnectDB.getResultSet(sql);
            System.out.println(sql);
    }
    
}
